<template>
  <el-card class="app-container">
    <form-selections :is-active="isActive" :items="formItems" :query-param.sync="queryParam" display="block" @handleSearch="handleSearch" />
    <div class="select_flex">
      <div class="operation_button_box">
        <el-button v-action="'orderRecords@orderConvert'" size="small" :disabled="selectedIds.length?false:true" type="success" @click="orderConvert">转为正常订单</el-button>
        <el-button v-action="'orderRecords@export'" size="small" :disabled="data.length?false:true" type="primary" :loading="exportLoading" @click="handleExport">导出</el-button>
        <el-button v-action="'orderRecords@orderAmazonImport'" size="small" type="primary" @click="formVisibleFile=true">导入亚马逊地址</el-button>
        <el-button v-action="'orderRecords@orderInvalidMore'" size="small" type="danger" :disabled="selectedIds.length?false:true" @click="getorderDelete">批量作废</el-button>
        <el-button v-action="'orderRecords@modifyGoodMapping'" size="small" type="primary" @click="modifyGoodMapping">批量修改商品</el-button>
      </div>
      <div>
        <el-button size="small" type="primary" class="filter-item search" icon="el-icon-search" @click="handleSearch">
          搜索
        </el-button>
        <el-button size="small" class="filter-item" icon="el-icon-refresh" @click="handleRefresh">
          重置
        </el-button>
        <el-button size="small" @click="isActive=!isActive">{{ isActive?'展开':'收起' }}</el-button>
      </div>
    </div>
    <el-table v-loading="loading" :data="data" :row-class-name="tableRowClassName" style="width: 100%;margin-bottom: 20px;" row-key="id" :max-height="screenHeigh" border default-expand-all :tree-props="{children: 'children', hasChildren: 'hasChildren'}" @selection-change="handleSelectMulti">
      <el-table-column type="selection" width="55" :selectable="checkSelectable" />
      <el-table-column label="序号" type="index" width="55" align="center" fixed />
      <el-table-column align="center" label="操作" width="250" fixed>
        <template slot-scope="sales">
          <span v-if="sales.row.status!==6 && sales.row.status!==5 && sales.row.abnormal==2" v-action="'orderRecords@update'" class="el-icon-edit pointer blue" @click="handleUpdateAddress(sales.row.id)">修改地址</span>
          <span v-if="sales.row.status!==6 && sales.row.status!==5 && sales.row.abnormal==1" v-action="'orderRecords@updateProduct'" class="el-icon-edit pointer edit_style" @click="handleUpdateProduct(sales.row)">修改商品</span>
          <span v-if="sales.row.status===1" v-action="'orderRecords@invalid'" class="delete_style" @click="handleInvalid('/orderRecords/invalid', sales.row.id)">作废</span>
        </template>
      </el-table-column>
      <!-- <el-table-column align="center" prop="order_no" label="订单编号" width="150" /> -->
      <el-table-column align="center" sortable prop="id" label="ID" width="100" />
      <el-table-column align="center" sortable prop="order_no" label="订单编号" width="150">
        <template slot-scope="scope">
          <span class="pointer blue" @click="$router.push({path: `/order/orderInfo/${scope.row.id}` ,query:{title: '异常订单'}})">{{ scope.row.order_no }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" sortable label="异常类型" prop="abnormal" width="150">
        <template slot-scope="scope">
          {{ scope.row.abnormal === 1 ? '商品异常' : (scope.row.abnormal===2 ? '地址异常' : '待转化') }}
        </template>
      </el-table-column>
      <el-table-column align="center" sortable prop="platform_no" label="平台订单编号" width="180" show-overflow-tooltip />
      <el-table-column align="center" prop="platform_no_ext" sortable label="平台订单编号2" width="180" show-overflow-tooltip />
      <el-table-column align="center" sortable prop="platform" label="平台" width="100" />
      <el-table-column align="center" sortable prop="shop_name" label="店铺名称" width="150" />
      <el-table-column align="center" prop="sku" sortable label="平台sku" min-width="180" />
      <el-table-column align="center" sortable prop="product_code" label="SKU编码" min-width="150" />
      <!-- <el-table-column align="center" sortable prop="sku_name" label="SKU名称" width="150" show-overflow-tooltip /> -->
      <!-- <el-table-column align="center" prop="goods_id" label="商品ID" /> -->
      <el-table-column align="center" sortable prop="category_text" label="商品分类" width="150">
        <template slot-scope="scope">
          {{ scope.row.category_text ? scope.row.category_text: '-' }}
        </template>
      </el-table-column>
      <el-table-column align="center" sortable prop="status_text" label="订单状态" width="120" />
      <el-table-column align="center" prop="name_ch" sortable label="中文名称" show-overflow-tooltip width="120" />
      <el-table-column align="center" prop="address_name" label="买家姓名" width="150" show-overflow-tooltip />
      <el-table-column align="center" prop="address_email" label="买家邮箱" width="150" show-overflow-tooltip />
      <el-table-column align="center" prop="address_phone" label="买家手机" width="150" />
      <el-table-column align="center" prop="address_stateorprovince" label="州" show-overflow-tooltip />
      <el-table-column align="center" prop="address_cityname" label="城市" show-overflow-tooltip />
      <el-table-column align="center" prop="address_postalcode" label="邮编" width="150" />
      <el-table-column align="center" prop="total_num" label="合计数量" />
      <el-table-column align="center" prop="order_source" sortable label="订单来源" width="120">
        <template slot-scope="scope">
          <!-- 0-平台接口;1-录入;2-导入 -->
          {{ scope.row.order_source===1 ? '录入': scope.row.order_source===2 ? '导入':'平台拉取' }}
        </template>
      </el-table-column>
      <el-table-column align="center" prop="after_sale_status" label="是否存在售后" width="120">
        <template slot-scope="scope">
          {{ scope.row.after_sale_status === 0 ? '否' : '是' }}
        </template>
      </el-table-column>
      <el-table-column align="center" prop="get_at" label="订单拉取时间" sortable width="165" />
      <el-table-column align="center" prop="creator_username" label="创建人" width="112">
        <template slot-scope="scope">
          <app-text :text="scope.row.creator_username" />
        </template>
      </el-table-column>
      <el-table-column align="center" prop="created_at" sortable label="创建时间" width="174" />
      <el-table-column align="center" prop="updater_username" label="修改人" width="112">
        <template slot-scope="scope">
          <app-text :text="scope.row.updater_username" />
        </template>
      </el-table-column>
      <el-table-column align="center" prop="updated_at" sortable label="修改时间" width="174" />
    </el-table>
    <el-pagination v-if="paginate.total > 0" class="pagination_box" background :current-page="paginate.current" :page-sizes="[50,100,200,500]" :page-size="queryParam.limit" layout="total, sizes, prev, pager, next, jumper" :total="paginate.total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    <!-------- 回到顶部 ------------>
    <el-backtop :visibility-height="200">
      <i class="el-icon-caret-top" />
    </el-backtop>
    <!--下载字段选择-->
    <DownModul :url="downloadxlsxUrl" :search-param="downLoadParams" :form-visible-down.sync="formVisibleDown" titel="异常订单导出字段选择" :options-modul="optionsModul" />
    <!-- 修改地址 -->
    <OrderAddress :id="orderId" :form-visible.sync="formVisibleAddress" title="修改订单地址" @handleRefresh="handleSearch" />
    <!-- 修改商品 -->
    <ChangeGoods :data="orderData" :form-visible-down.sync="formVisibleModify" @handleSearch="handleSearch" />
    <!-- 导人 -->
    <ImportDialog url="/orderRecords/amazon/import" title="导入亚马逊地址" :form-visible.sync="formVisibleFile" @download="downLoad" @handleRefresh="handleSearch" />
    <el-dialog :center="true" title="销售订单批量作废" :visible.sync="formVisibleDelete" width="700px">
      <div class="from_box">
        <el-form ref="ruleForm" label-width="140px" class="demo-ruleForm">
          <el-form-item :label="`已选择订单(${selectedCodes.length}个):`">
            {{ selectedCodes }}
          </el-form-item>
        </el-form>
      </div>
      <div style="text-align: center;">确定作废吗？</div>
      <div style="text-align: center;margin-top:20px;">
        <el-button type="primary" :loading="isbtn" @click="submitDelete">确定</el-button>
        <el-button @click="formVisibleDelete = false">取消</el-button>
      </div>
    </el-dialog>
  </el-card>
</template>

<script>
import formOperate from '@/layout/mixin/formOperate'
import {
  action
} from '@/directive/permission/index.js' // 权限判断指令
import DownModul from '@/components/DownModul/index.vue'
import OrderAddress from '@/components/OrderAddress/index.vue'
import ChangeGoods from './component/changeGoods.vue'
import appText from '@/components/appText/index'
import FormSelections from '@/components/FormSelection'
import ImportDialog from '@/components/importDialog/index.vue'
import { downloadStream } from '@/utils/index'
export default {
  name: 'OrderAbnormal',
  directives: {
    action
  },
  components: { DownModul, OrderAddress, ChangeGoods, appText, FormSelections, ImportDialog },
  mixins: [formOperate],
  data() {
    return {
      otherHeight: 405,
      secondUrl: 1,
      isbtn: false,
      importUrl: '',
      formVisibleFile: false,
      formVisibleDelete: false,
      searchClass: 1,
      searchShop: 1,
      formItems: [
        {
          label: '订单编号',
          key: 'order_no',
          type: 'input',
          placeholder: '请输入订单编号'
        },
        {
          label: '平台名称',
          key: 'platform_name',
          type: 'input',
          placeholder: '请输入平台'
        },
        {
          label: '店铺',
          key: 'shop_id',
          type: 'select',
          multiple: true,
          filterable: true,
          placeholder: '请选择店铺',
          options: []
        },
        {
          label: '系统SKU',
          key: 'goods_code',
          type: 'input',
          placeholder: '请输入系统SKU'
        },
        {
          label: '中文名称',
          key: 'name_ch',
          type: 'input',
          placeholder: '请输入中文名称'
        },
        {
          label: '商品分类',
          key: 'category_ids',
          type: 'cascader',
          cLabel: 'lable',
          cValue: 'value',
          options: []
        },
        {
          label: '订单状态',
          key: 'status',
          type: 'select',
          placeholder: '请选择订单状态',
          options: [
            {
              label: '待发货',
              value: '1'
            },
            {
              label: '发货中',
              value: '2'
            },
            {
              label: '已发货',
              value: '3'
            },
            {
              label: '作废订单',
              value: '6'
            }
          ]
        },
        {
          label: '异常类型',
          key: 'abnormal',
          type: 'select',
          placeholder: '请选择异常类型',
          options: [
            {
              label: '商品异常',
              value: '1'
            },
            {
              label: '地址异常',
              value: '2'
            },
            {
              label: '待转化',
              value: '3'
            }
          ]
        },
        {
          label: '订单来源',
          key: 'order_source',
          type: 'select',
          placeholder: '请选择订单来源',
          options: [
            {
              label: '平台拉取',
              value: '0'
            },
            {
              label: '录入',
              value: '1'
            },
            {
              label: '导入',
              value: '2'
            }
          ]
        },
        {
          label: '买家州/省',
          key: 'state',
          type: 'input',
          placeholder: '请输入州'
        },
        {
          label: '买家城市',
          key: 'city_name',
          type: 'input',
          placeholder: '请输入城市'
        },
        {
          label: '买家姓名',
          key: 'user_name',
          type: 'input',
          placeholder: '请输入买家姓名'
        },
        {
          label: '买家邮箱',
          key: 'email',
          type: 'input',
          placeholder: '请输入邮箱'
        },
        {
          label: '拉取日期',
          key: 'date',
          type: '',
          //   valueFormat: 'timestamp',
          valueFormat: 'yyyy-MM-dd HH:mm:ss',
          placeholder: '请选择时间范围'
          //   wrap: true
        },
        {
          label: '生成日期',
          key: 'dateCreat',
          type: '',
          valueFormat: 'yyyy-MM-dd HH:mm:ss',
          placeholder: '请选择时间范围'
          //   wrap: true
        }
      ],
      componentName: 'OrderAbnormal',
      cachePaths: [
        '/order/orderInfo',
        '/order/orderAdd'
      ],
      downloadxlsxUrl: '/orderRecords/export',
      orderData: {},
      formVisibleModify: false,
      formVisibleAddress: false,
      formVisibleDown: false,
      loading: false,
      select: 'shop_name',
      formName: 'orderRecords',
      formLabelWidth: '90px',
      // 刷新路由
      refreshRoute: true,
      queryParam: {
        start_at: '',
        end_at: '',
        status: '',
        // type: 1,
        abnormal: '',
        is_abnormal: '1,2,3',
        limit: 50
      },
      fiftyLimit: 50,
      defaultQueryParam: ['is_abnormal'],
      url: 'orderRecords',
      optionsModul: [
        {
          key: 'order_ids',
          label: '订单ID'
        },
        {
          key: 'order_no',
          label: '订单编号'
        },
        {
          key: 'platform_no',
          label: '平台订单编号'
        },
        {
          key: 'platform',
          label: '平台名称'
        },
        {
          key: 'shop_name',
          label: '店铺名称'
        },
        {
          key: 'name_ch',
          label: '商品名称'
        },
        {
          key: 'category_names',
          label: '商品分类'
        },
        {
          key: 'goods_code',
          label: '系统SKU'
        },
        {
          key: 'sku',
          label: '平台SKU'
        },
        {
          key: 'quantity_purchased',
          label: '总个数'
        },
        {
          key: 'transaction_price_currencyid',
          label: '币别'
        },
        {
          key: 'total_amount',
          label: '总金额（含税）'
        },
        {
          key: 'tax_amount_value_all',
          label: '税费'
        },
        {
          key: 'status_text',
          label: '订单状态'
        },
        {
          key: 'company_name',
          label: '所属公司'
        },
        {
          key: 'address_name',
          label: '买家姓名'
        },
        {
          key: 'buyer_email',
          label: '买家邮箱'
        },
        {
          key: 'address_phone',
          label: '电话号码'
        },
        {
          key: 'address_postalcode',
          label: '邮编'
        },
        {
          key: 'address_country',
          label: '国家'
        },
        {
          key: 'address_stateorprovince',
          label: '州'
        },
        {
          key: 'address_cityname',
          label: '城市'
        },
        {
          key: 'address_street1',
          label: '街道'
        },
        {
          key: 'created_at',
          label: '订单生成时间'
        },
        {
          key: 'get_at',
          label: '订单拉取时间'
        },
        {
          key: 'shipped_at',
          label: '发货时间'
        }
      ],
      orderId: ''
    }
  },
  activated() {
    this.getList()
  },
  methods: {
    modifyGoodMapping() {
      const list = this.data.filter((arr) => {
        return this.selectedIds.includes(arr.id) && arr.abnormal === 1
      })
      const orderNoData = list.map((arr) => {
        return arr.order_no
      })
      if (orderNoData.length < 1) {
        this.$message.info('暂无符合条件订单')
        return false
      }
      const listNew = orderNoData.join('</br>')

      this.$confirm(`<div>确认批量处理异常订单<p style="max-height: 400px;overflow-y: auto;">${listNew}</p>商品异常？<div>`, '提示', {
        dangerouslyUseHTMLString: true,
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http1.post(`/orderRecords/modifyGoodMapping`, {
          orders: orderNoData
        }).then((res) => {
          if (res.code === 10000) {
            this.$message.success('操作成功')
            // 成功数量
            const successNumber = res.data.success ? res.data.success.length : 0
            // 品配失败数量
            const emptyNumber = res.data.fail ? res.data.fail.length : 0
            this.$notify.info({
              title: '处理结果',
              message: `处理成功${successNumber}个，处理失败数量${emptyNumber}个`,
              duration: 4500
            })
            this.handleSearch()
          }
        }).catch(() => {
        })
      })
    },
    // 下载
    downLoad() {
      const vm = this
      vm.$http
        .get('/orderRecords/import/amazon/template', { responseType: 'blob' })
        .then((res) => {
          downloadStream(res, '亚马逊地址导入模板.xlsx')
        })
    },
    // 导出
    handleExport() {
      const vm = this
      const params = {}
      const object = this.queryParam
      for (const key in object) {
        if (Object.hasOwnProperty.call(object, key)) {
          const element = object[key]
          params[key] = element
        }
      }
      vm.downLoadParams = params
      vm.formVisibleDown = true
    },
    beforeSearch() {
      const vm = this
      const { abnormal } = vm.queryParam
      if (abnormal) {
        delete vm.queryParam.is_abnormal
      } else {
        vm.queryParam.is_abnormal = '1,2,3'
      }
      vm.queryParam.start_at_pay = ''
      vm.queryParam.end_at_pay = ''
      vm.queryParam.start_at = ''
      vm.queryParam.end_at = ''
      vm.queryParam.start_at_creat = ''
      vm.queryParam.end_at_creat = ''
      vm.queryParam.shop_ids = ''
      if (vm.queryParam.shop_id && vm.queryParam.shop_id.length > 0) {
        vm.queryParam.shop_ids = vm.queryParam.shop_id.join(',')
      }
      if (vm.queryParam.date && vm.queryParam.date.length > 0) {
        vm.queryParam.start_at = vm.queryParam.date[0]
        vm.queryParam.end_at = vm.queryParam.date[1]
      }
      // 生成日期转化
      if (vm.queryParam.dateCreat && vm.queryParam.dateCreat.length > 0) {
        vm.queryParam.start_at_creat = vm.queryParam.dateCreat[0]
        vm.queryParam.end_at_creat = vm.queryParam.dateCreat[1]
      }
      if (vm.queryParam.category_ids && vm.queryParam.category_ids.length > 0) {
        // vm.queryParam.category_id = vm.queryParam.category_ids.pop()
        const arr = vm.queryParam.category_ids
        vm.queryParam.category_id = arr[arr.length - 1]
      } else {
        vm.queryParam.category_id = ''
      }
    },
    // 设置禁止选择项
    checkSelectable(row, index) {
      return true
    },
    // 修改商品信息
    handleUpdateProduct(data) {
      this.orderData = {
        'id': data.id,
        'shop_id': data.shop_basics_id,
        'platform_code': data.sku
      }
      this.formVisibleModify = true
    },
    // 编辑
    handleUpdateAddress(id) {
      this.orderId = id + ''
      this.formVisibleAddress = true
    },
    // 正常订单
    orderConvert() {
      const vm = this
      if (vm.selectedIds.length > 1) {
        return vm.$message.error('请至多选择一条数据')
      }
      console.log(this.data)
      const id = vm.selectedIds[0]
      if (this.data.find(v => v.id === id).abnormal !== 3) {
        return vm.$message.error('该订单无法转为正常订单')
      }
      vm.$confirm('确认将此异常订单转化为正常订单？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.put(`/orderRecords/orderConvert/${id}`).then((response) => {
          if (response.code === 10000) {
            this.$message.success(`成功转化为->${response.data}`)
            this.handleRefresh()
          }
        })
      }).catch(() => { })
    },
    // 批量作废
    getorderDelete() {
      const vm = this
      const list = this.data.filter((arr) => {
        return this.selectedIds.includes(arr.id) && arr.logistics_status === 0
      })
      const ids = list.map((arr) => {
        return arr.id
      })
      vm.selectedIds = ids
      vm.selectedCodes = list.map((arr) => {
        return arr.order_no
      })
      vm.formVisibleDelete = true
    },
    submitDelete() {
      this.isbtn = true
      this.$http.post(`/orderRecords/orderInvalidMore`, { ids: this.selectedIds }).then(res => {
        if (res.code === 10000) {
          this.$message.success('操作成功')
          this.formVisibleDelete = false
          this.handleSearch()
          this.isbtn = false
        } else {
          this.isbtn = false
        }
      }).catch(() => {
        this.isbtn = false
      })
    }
  }
}
</script>
